package com.testcase.splash;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.sensetecnic.client.SenseTecnicClient;
import com.sensetecnic.client.SenseTecnicException;
import com.testcase.R;
import com.testcase.SensorListClick;

public class SplashScreen extends Activity {
	
	private static final int DIALOG_LOGIN = 0;
	private static final int DIALOG_FAIL = 1;
	private boolean authorization;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Set the View from the XML Design
		setContentView(R.layout.splash);
		//Refer to the button element using findViewById
		Button but = (Button) findViewById(R.id.loginbutton);
		//Try to get username or password if the user already logged in using sharedpreferences
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    	Resources reso = getResources();
		String username = pref.getString(reso.getString(R.string.stsUsernameKey), null);
    	String password = pref.getString(reso.getString(R.string.stsPasswordKey), null);
    	authorization = SplashScreen.isAuth(username, password);
    	
    	//Add listener button to show dialog if they have not logged in before
    	//or can't connect to the internet
		but.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!authorization) {
					showDialog(DIALOG_LOGIN);
				}
				else {
					//Start new activity if they are logged in (sensor list) and finish/terminate
					//this activity
					Intent intent = new Intent(SplashScreen.this, SensorListClick.class);
					startActivity(intent);
					finish();
				}
			}
		});
	}
	
	//Dialog creation
	@Override
    protected Dialog onCreateDialog(int id) {
		switch (id) {
        case DIALOG_LOGIN:
        	LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
            return new AlertDialog.Builder(SplashScreen.this)
                .setTitle(R.string.loginSense)
                .setView(textEntryView)
                .setPositiveButton(R.string.logincheck, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	AlertDialog ad = (AlertDialog) dialog;
                    	EditText etu = (EditText) ad.findViewById(R.id.username_edit);
                    	EditText etp = (EditText) ad.findViewById(R.id.password_edit);
                    	String username = etu.getText().toString();
                    	String password = etp.getText().toString();
                    	Boolean auth = SplashScreen.isAuth(username, password);
                    	if(auth) {
                    		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    		Editor edit = pref.edit();
                    		Resources reso = getApplicationContext().getResources();
                    		edit.putString(reso.getString(R.string.stsUsernameKey), username);
                    		edit.putString(reso.getString(R.string.stsPasswordKey), password);
                    		edit.commit();
                    		Intent intent = new Intent(SplashScreen.this, SensorListClick.class);
    						startActivity(intent);
    						finish();
                    	}
                    	else {
                    		dismissDialog(DIALOG_LOGIN);
                    		showDialog(DIALOG_FAIL);
                    	}
                    }
                    		
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .create();
        case DIALOG_FAIL:
        	return new AlertDialog.Builder(SplashScreen.this)
            .setTitle(R.string.faillogin)
            .setMessage(R.string.incorrect)
            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	dismissDialog(DIALOG_FAIL);
                	showDialog(DIALOG_LOGIN);
                }
            })
            .create();
		}
		return null;
	}
	
	//Check if user has logged in before by sending a http request to the SenseTecnic
	//If the user and pass do not work on the SenseTecnic site return false
	public static Boolean isAuth(String user, String pass) {
    	if(user == null || pass == null) {
    		return false;
    	}
    	
    	SenseTecnicClient client = new SenseTecnicClient();
    	client.setStsBaseUrl("http://demo.sensetecnic.com/SenseTecnic");
    	try {
    		client.getHtml(user, pass, "/spring/sensors/");
    	} catch(SenseTecnicException e) {
    		return false;
    	}
    	return true;
	}
}
